(import
  (except (rnrs base) let-values map error)
  (only (guile) lambda* λ command-line string-null?)
  ;; (ice-9 peg)
  (srfi srfi-1)
  (fileio))


(define forward? (λ (char) (char=? char #\F)))
(define backward? (λ (char) (char=? char #\B)))
(define right? (λ (char) (char=? char #\R)))
(define left? (λ (char) (char=? char #\L)))


(define lower-half-interval
  (λ (min-num max-num)
    (cons min-num
          (floor
           (- max-num
              (/ (- max-num min-num) 2))))))


(define upper-half-interval
  (λ (min-num max-num)
    (cons (ceiling
           (+ min-num
              (/ (- max-num min-num) 2)))
          max-num)))


(define line->seat
  (lambda* (line #:key (num-rows 128) (num-cols 8))
    (let ([chars (string->list line)])
      (let next-char ([remaining-chars chars]
                      [row-range (cons 0 (- num-rows 1))]
                      [col-range (cons 0 (- num-cols 1))])
        (cond
         [(null? remaining-chars) (cons row-range col-range)]
         [(forward? (car remaining-chars))
          (next-char (cdr remaining-chars)
                     (lower-half-interval (car row-range) (cdr row-range))
                     col-range)]
         [(backward? (car remaining-chars))
          (next-char (cdr remaining-chars)
                     (upper-half-interval (car row-range) (cdr row-range))
                     col-range)]
         [(left? (car remaining-chars))
          (next-char (cdr remaining-chars)
                     row-range
                     (lower-half-interval (car col-range) (cdr col-range)))]
         [(right? (car remaining-chars))
          (next-char (cdr remaining-chars)
                     row-range
                     (upper-half-interval (car col-range) (cdr col-range)))]
         [else
          (error "unexpected char" (car remaining-chars))])))))


(define seat-row
  (λ (seat)
    (car (car seat))))


(define seat-col
  (λ (seat)
    (car (cdr seat))))


(define seat->seat-id
  (lambda* (seat #:key (row-width 8))
    (let ([row (seat-row seat)]
          [col (seat-col seat)])
      (+ (* row row-width) col))))


(define main
  (λ (cmd-line-args)
    (let* ([lines (get-lines-from-file (second cmd-line-args))]
           [seats (map line->seat lines)]
           [seat-ids (map seat->seat-id seats)])
      (apply max seat-ids))))


(simple-format (current-output-port)
               "~a\n"
               (main (command-line)))
